#include "loginwindow.h"
#include "ui_loginwindow.h"
#include "LoginWindow.h"
#include "ui_LoginWindow.h"
#include <QPainter>
#include <QMovie>
#include <QHBoxLayout>
#include <QCursor>
#include <QMenu>
#include <QDebug>
#include <QTime>
#include "accountitem.h"
#include <QPropertyAnimation>

#define TRANSLATE_WIDTH 80

static const char *userNameInit[]={"dy","xf","xz"};

LoginWindow::LoginWindow(QWidget *parent)
    : BaseWindow(parent)
    , ui(new Ui::LoginWindow)
    , m_loginState(ONLINE)
    , m_view(&m_scene)
    , m_isPressed(false)
    , m_graphicsWidget(NULL)
{
    ui->setupUi(this);
    initWindow();
    initMyTitle();
    initAccountList();
    this->loadStyleSheet(":/qss/qss/loginWindow.css");
    connect(m_titleBar, SIGNAL(signalButtonMinClicked()), this, SIGNAL(hideWindow()));
    /* 连接数据库 */
    m_styDatabase = new styDatabase;
    if(m_styDatabase->createConnection())
        qDebug()<<"连接成功"<<endl;
    else
        this->close();
}

LoginWindow::~LoginWindow()
{
    delete ui;
}

// 初始化标题栏;
void LoginWindow::initMyTitle()
{
    // 因为这里有控件层叠了，所以要注意控件raise()方法的调用顺序;
    m_titleBar->move(0, 0);
    m_titleBar->raise();
    m_titleBar->setBackgroundColor(0, 0, 0, true);
    m_titleBar->setButtonType(MIN_BUTTON);
    m_titleBar->setTitleWidth(this->width());
    // 允许通过标题栏拖动来移动窗口位置
    m_titleBar->setMoveParentWindowFlag(true);
    ui->pButtonArrow->raise();

    QIcon icon(":/img/img/time.ico");
    this->setWindowIcon(icon);
}

// 初始化窗口;
void LoginWindow::initWindow()
{
    //背景GIG图;
    QLabel* pBack = new QLabel(this);
    //QMovie *movie = new QMovie();
    //movie->setFileName(":/img/img/login/back.gif");
    //pBack->setMovie(movie);
    //movie->start();
    //pBack->setFixedSize(QSize(480,200));

    pBack->setMinimumSize(430,180);
    pBack->setMaximumSize(430,180);
    QPixmap pixmap(":img/img/login/pen.png");
    QPixmap img=pixmap.scaled(pBack->size(),Qt::KeepAspectRatio);
    pBack->setScaledContents(true);
    pBack->setPixmap(img);
    pBack->move(0, 0);

    //暗注释;
    ui->accountComboBox->setEditable(true);
    QLineEdit* lineEdit = ui->accountComboBox->lineEdit();
    lineEdit->setPlaceholderText(QStringLiteral("QQ号码/手机/邮箱"));

    ui->passwordEdit->setPlaceholderText(QStringLiteral("密码"));

    // 密码框中的小键盘按钮;
    m_keyboardButton = new QPushButton();
    m_keyboardButton->setObjectName("pButtonKeyboard");
    m_keyboardButton->setFixedSize(QSize(16, 16));
    m_keyboardButton->setCursor(QCursor(Qt::PointingHandCursor));

    QHBoxLayout* passwordEditLayout = new QHBoxLayout();
    passwordEditLayout->addStretch();
    passwordEditLayout->addWidget(m_keyboardButton);
    passwordEditLayout->setSpacing(0);
    passwordEditLayout->setContentsMargins(0, 0, 8, 0);

    ui->passwordEdit->setLayout(passwordEditLayout);
    ui->passwordEdit->setTextMargins(0, 0, m_keyboardButton->width() + 12, 0);

    QPixmap head0(":img/img/login/HeadImage.png");
    QPixmap head1=head0.scaled(ui->userHead->size(),Qt::KeepAspectRatio);
    ui->userHead->setScaledContents(true);
    ui->userHead->setPixmap(head1);

    ui->loginState->setIcon(QIcon(":/img/img/LoginState/state_online.png"));
    ui->loginState->setIconSize(QSize(13, 13));

    connect(ui->loginState, SIGNAL(clicked()), this, SLOT(onLoginStateClicked()));
    connect(ui->pButtonArrow, SIGNAL(clicked()), this, SLOT(onNetWorkSet()));
}

// 初始化用户登录信息;
void LoginWindow::initAccountList()
{
    // 添加三个测试用户;
    m_Accountlist = new QListWidget(this);
    ui->accountComboBox->setModel(m_Accountlist->model());
    ui->accountComboBox->setView(m_Accountlist);

    for (int i = 0; i < 3; i++)
    {
        AccountItem *account_item = new AccountItem();
        account_item->setAccountInfo(i,userNameInit[i],QString(":/img/img/headImage/head%1.png").arg(i),1);
        connect(account_item, SIGNAL(signalShowAccountInfo(int, QString)), this, SLOT(onShowAccountInfo(int, QString)));
        connect(account_item, SIGNAL(signalRemoveAccount(int)), this, SLOT(onRemoveAccount(int)));
        QListWidgetItem *list_item = new QListWidgetItem(m_Accountlist);
        m_Accountlist->setItemWidget(list_item, account_item);
    }
}

// 选择了新的用户登录状态;
void LoginWindow::onLoginStateClicked()
{
    m_loginStateMemu = new QMenu();
    QAction *pActionOnline = m_loginStateMemu->addAction(QIcon(":/img/img/LoginState/state_online.png"), QStringLiteral("在线"));
    QAction *pActionActive = m_loginStateMemu->addAction(QIcon(":/img/img/LoginState/state_Qme.png"), QStringLiteral("Q我吧"));
    m_loginStateMemu->addSeparator();
    QAction *pActionAway = m_loginStateMemu->addAction(QIcon(":/img/img/LoginState/state_away.png"), QStringLiteral("离开"));
    QAction *pActionBusy = m_loginStateMemu->addAction(QIcon(":/img/img/LoginState/state_busy.png"), QStringLiteral("忙碌"));
    QAction *pActionNoDisturb = m_loginStateMemu->addAction(QIcon(":/img/img/LoginState/state_notdisturb.png"), QStringLiteral("勿扰"));
    m_loginStateMemu->addSeparator();
    QAction *pActionHide = m_loginStateMemu->addAction(QIcon(":/img/img/LoginState/state_hide.png"), QStringLiteral("隐身"));
    // 设置状态值;
    pActionOnline->setData(ONLINE);
    pActionActive->setData(ACTIVE);
    pActionAway->setData(AWAY);
    pActionBusy->setData(BUSY);
    pActionNoDisturb->setData(NOT_DISTURB);
    pActionHide->setData(HIDE);


    connect(m_loginStateMemu, SIGNAL(triggered(QAction *)), this, SLOT(onMenuClicked(QAction*)));

    QPoint pos = ui->loginState->mapToGlobal(QPoint(0, 0)) + QPoint(0, 20);
    m_loginStateMemu->exec(pos);
}

// 用户状态菜单点击;
void LoginWindow::onMenuClicked(QAction * action)
{
    ui->loginState->setIcon(action->icon());
    // 获取状态值;
    m_loginState = (LoginState)action->data().toInt();
    qDebug() << "onMenuClicked" << m_loginState;
}

//将选项文本显示在QComboBox当中
void LoginWindow::onShowAccountInfo(int index, QString accountName)
{
    ui->accountComboBox->setEditText(accountName);
    ui->accountComboBox->hidePopup();
    ui->passwordEdit->setText("psd"+accountName);
    ui->rememberPsd->setChecked(true);

    // 更换用户头像;
    QString fileName = QString(":/img/img/headImage/head%1.png").arg(index);
    ui->userHead->setPixmap(QPixmap(fileName).scaled(ui->userHead->width(), ui->userHead->height()));
}

void LoginWindow::onNetWorkSet()
{
    emit rotateWindow();
}

// 以下通过mousePressEvent、mouseMoveEvent、mouseReleaseEvent三个事件实现了鼠标拖动标题栏移动窗口的效果;
void LoginWindow::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)
    {
        m_isPressed = true;
        m_startMovePos = event->globalPos();
    }
    //qDebug()<<"hzq->mousePressEvent:";
    return QWidget::mousePressEvent(event);
}

void LoginWindow::mouseMoveEvent(QMouseEvent *event)
{
    //qDebug()<<"hzq->mouseMoveEvent:"<<m_isPressed;
    if (m_isPressed)
    {
        QPoint movePoint = event->globalPos() - m_startMovePos;
        //QPoint widgetPos = this->parentWidget()->pos() + movePoint;
        QPoint widgetPos = this->pos() + movePoint;
        m_startMovePos = event->globalPos();
        //this->parentWidget()->move(widgetPos.x(), widgetPos.y());   //这一句得注释掉，不然会发生段错误
        this->move(widgetPos.x(), widgetPos.y());
        //qDebug()<<"this:"<<this->objectName()<<", "<<this->metaObject()->className();
    }
    return QWidget::mouseMoveEvent(event);
}

void LoginWindow::mouseReleaseEvent(QMouseEvent *event)
{
    m_isPressed = false;
    //qDebug()<<"hzq->mouseReleaseEvent:"<<m_isPressed;
    return QWidget::mouseReleaseEvent(event);
}

void LoginWindow::closeEvent(QCloseEvent *event)
{
    emit closeWindow();
    ///return __super::closeEvent(event);
    return QWidget::closeEvent(event);
}

void LoginWindow::onRemoveAccount(int index)
{
    for (int row = 0; row < m_Accountlist->count(); row++)
    {
        AccountItem* itemWidget = (AccountItem*)m_Accountlist->itemWidget(m_Accountlist->item(row));
        if (itemWidget != NULL && itemWidget->getItemWidgetIndex() == index)
        {
            m_Accountlist->takeItem(row);
            itemWidget->deleteLater();
        }
    }
}

void LoginWindow::on_loginButton_clicked()
{
    ui->loginButton->setText(QString("登陆中..."));
    ui->loginButton->setCheckable(false);
    ui->loginButton->setStyleSheet("background-color: rgb(209 , 209 , 209);");
    ui->loginButton->repaint();
    if(m_styDatabase->userAuthenticate(ui->accountComboBox->currentText(),ui->passwordEdit->text())){
        //qDebug()<<"file:"<<__FILE__<<"line:"<<__LINE__;
        main = new Widget();
        //main->m_main_left->getEveryoneData();
        this->hide();
        sthread = new mythread(ui->accountComboBox->currentText(),ui->passwordEdit->text());
        sthread->start();
        connect(sthread,SIGNAL(sigStudyStatuschanged(qint64)),
                main->m_main_right->m_study_widget->m_top_widget,
                SLOT(onPenStatusChanged(qint64)));
        main->showMaximized();
        main->setWidgetsSize();
    }else{
        QMessageBox::warning(this, tr("登陆时错误"),
                 tr("<h2>您输入的账户名或密码不正确,原因可能是：</h2>"
                 "<p> 1、账户名输入有误</p>"
                 "<p> 2、忘记密码</p>"
                 "<p> 3、未区分字母大小写</p>"
                 "<p> 4、未开启小键盘</p>"
                 "<p> 5、账户名未绑定笔的编号</p>"
                 "<p> </p>"
                    ));
    }
    ui->loginButton->setCheckable(true);
    ui->loginButton->setStyleSheet("background-color:rgb(14 , 150 , 254);");
    ui->loginButton->setText(QString("登陆"));
    ui->loginButton->repaint();
}
